package com.hwl.eduservice.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hwl.commonutils.exception.GuliException;
import com.hwl.commonutils.result.ResultCodeEnum;
import com.hwl.eduservice.listener.ExcelSubjectDataListener;
import com.hwl.eduservice.mapper.SubjectMapper;
import com.hwl.eduservice.pojo.Subject;
import com.hwl.eduservice.pojo.excel.ExcelSubjectData;
import com.hwl.eduservice.service.SubjectService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author long
 * @since 2021-09-21
 */
@Slf4j
@Service
public class SubjectServiceImpl extends ServiceImpl<SubjectMapper, Subject> implements SubjectService {

    @Override
    public void batchImport(MultipartFile file) {
        try {
            //所有的一级分类以及对应的二级分类
            Map<String, Set<String>> map = new HashMap<>();

            List<Subject> oneSubject = this.getOneSubject();
            for (Subject subject : oneSubject) {
                Set<String> twoSubjectTitle = this.getTwoSubject(subject.getId()).stream().map(Subject::getTitle).collect(Collectors.toSet());
                map.put(subject.getTitle(), twoSubjectTitle);
            }

            log.info("开始批量导入课程分类~");
            EasyExcel.read(file.getInputStream(), ExcelSubjectData.class, new ExcelSubjectDataListener(baseMapper, map))
                    .excelType(ExcelTypeEnum.XLS).sheet().doRead();

            log.info("批量导入课程分类成功！");
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new GuliException(ResultCodeEnum.EXCEL_DATA_IMPORT_ERROR);
        }
    }

    @Override
    public List<Subject> getOneSubject() {
        return baseMapper.selectList(new QueryWrapper<Subject>().eq("parent_id", 0));
    }

    @Override
    public List<Subject> getTwoSubject(String oneTitleId) {
        return baseMapper.selectList(new QueryWrapper<Subject>().eq("parent_id", oneTitleId));
    }

    @Override
    public List<Subject> nestedList() {
        return baseMapper.selectNestedListByParentId("0");
    }
}
